package mysql_utils

import (
	"database/sql"
	"fmt"
	"sync"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"mongodb_connection_monitor/pkg/load_config"
)

var (
	once   sync.Once
	db     *sql.DB
	gormDb *gorm.DB
)

func GetDBInstance() *sql.DB {
	once.Do(func() {
		var err error
		db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
			load_config.GlobalConfig.MySQLConfig.MySQLUsername,
			load_config.GlobalConfig.MySQLConfig.MySQLPassword,
			load_config.GlobalConfig.MySQLConfig.MySQLHost,
			load_config.GlobalConfig.MySQLConfig.MySQLPort,
			load_config.GlobalConfig.MySQLConfig.MySQLDatabase,
		))
		if err != nil {
			fmt.Println("DB connection failed:", err)
			return
		}
		db.SetMaxOpenConns(load_config.GlobalConfig.MySQLConfig.MaxOpenConns)
		db.SetMaxIdleConns(5)
	})
	return db
}

func GetDBInstanceGorm() *gorm.DB {
	once.Do(func() {
		var (
			mySQLHost     string
			mySQLPort     int
			mySQLUser     string
			mySQLpassword string
			mySQLdataBase string

			dbConfig *load_config.Config
		)
		dbConfig = load_config.LoadConfig()

		mySQLHost = dbConfig.MySQLConfig.MySQLHost
		mySQLPort = dbConfig.MySQLConfig.MySQLPort
		mySQLUser = dbConfig.MySQLConfig.MySQLUsername
		mySQLpassword = dbConfig.MySQLConfig.MySQLPassword
		mySQLdataBase = dbConfig.MySQLConfig.MySQLDatabase

		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", mySQLUser, mySQLpassword, mySQLHost, mySQLPort, mySQLdataBase)
		gormDb, _ = gorm.Open(mysql.Open(dsn), &gorm.Config{CreateBatchSize: 1000})
	})
	return gormDb
}
